import styles from "./index.module.scss";
import type { FC } from "react";
import { useEffect, useRef, useState } from "react";
import { SVG_DATA, XML_DATA } from "./constant";
import { base64ToSvgString, stringToSvg, stringToXml, xmlToString } from "./utils";
import { clearElement } from "./utils";
import ReactDOM from "react-dom";
import { diagramLoader } from "./diagram-loader";

export const DiagramExample: FC = () => {
  const [loading, setLoading] = useState(true);
  const [xmlExample, setXMLExample] = useState(XML_DATA);
  const xmlExampleContainer = useRef<HTMLDivElement>(null);

  useEffect(() => {
    diagramLoader().then(() => {
      setLoading(false);
    }); // Preload Diagram
  }, []);

  const convertXML = (xml: string = xmlExample) => {
    const div = xmlExampleContainer.current;
    if (div) {
      diagramLoader().then(diagram => {
        const diagramViewer = new diagram.DiagramViewer(stringToXml(xml));
        const svg = diagramViewer.renderSVG(null, 1, 1);
        diagramViewer.destroy();
        clearElement(div);
        svg && div.appendChild(svg);
      });
    }
  };

  const editXML = () => {
    diagramLoader().then(diagram => {
      const renderExit = (el: HTMLDivElement) => {
        ReactDOM.render(
          <div>
          <div onClick={diagramEditor.exit} className="diagram-exit-btn">
            退出
          </div>
          {/* <div onClick={diagramEditor.exit} className="diagram-exit-btn">获取 XML 字符串</div> */}
        </div>,

          el
        );
      };

      const diagramEditor = new diagram.DiagramEditor(document.body, renderExit);
      diagram.getLanguage("zh").then(res => {
        // 从POST请求中获取XML数据
        fetch('https://8c5f3219-d9d2-4c17-beee-f3a5c4a79154.mock.pstmn.io/1', {
          method: 'POST',
          headers: {
            // 'Content-Type': 'application/json'
            // 如果需要，可以添加其他头部信息
          },
          // body: JSON.stringify({ /* 添加POST请求需要的任何数据 */ })
        })
        .then(response => response.text())
        .then(xmlExample => {
          diagramEditor.start(res, stringToXml(xmlExample), (xml: Node) => {
            const xmlString = xmlToString(xml);
            xmlString && setXMLExample(xmlString);
            // xmlString && convertXML(xmlExample);
          });

            // const xml =stringToXml(xmlExample);
            // const xmlString = xmlToString(xml);
            // xmlString && setXMLExample(xmlExample);
            // xmlString && convertXML(xmlExample);

        })
        .catch(error => console.error('Error fetching XML data:', error));
      });
    });
  };

  return (
    <div>
      {loading ? (
        <>资源加载中...</>
      ) : (
        <>
          <div>MxGraph XML</div>
          <div className={styles.example}>
            <div>
            <textarea cols={30} rows={10} value={xmlExample} onChange={(e) => setXMLExample(e.target.value)} />
            </div>
            <div className={styles.buttonGroup}>
              <button onClick={() => convertXML()}>显示图像</button>
              <button onClick={editXML}>在线编辑</button>
            </div>
            <div ref={xmlExampleContainer}></div>
          </div>

        </>
      )}
    </div>
  );
};
